package com.mgr.controller;

import java.util.Date;
import java.util.ResourceBundle;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import javax.transaction.Transaction;

import com.mgr.dao.CustomerDao;
import com.mgr.dao.TransactionDao;
import com.mgr.model.Accounts;
import com.mgr.model.Customers;
import com.mgr.model.Transactions;
import com.mgr.service.CustomerService;
import com.mgr.service.OTPService;
import com.mgr.service.SmsService;
import com.mgr.service.TransactionService;

import com.mgr.service.AccountService;

@Controller
public class InternalTransferController5 {

	@Autowired
	private AccountService accountService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private OTPService otpService;

	@Autowired
	private SmsService smsService;

	@Autowired
	private TransactionDao transactionDao;
	@Autowired
	private TransactionService transactionService;

	private ResourceBundle rb = ResourceBundle
			.getBundle("com.mgr.messages.errorMessage");

	@RequestMapping("/internaltransfer4")
	public ModelAndView setFormTransfer(HttpSession session,
			@RequestParam("accId2") int accId2,
			@RequestParam("amount") int amount,
			@RequestParam("otpCode") String otpCode) {
		int countTran = (Integer) session.getAttribute("countTran");
		ModelAndView modelAndView = new ModelAndView(
				"internaltransferresult.tile");
		if (session.getAttribute("user") == null) {
			session.invalidate();
			modelAndView.setViewName("login");
		} else {
			if (session.getAttribute("otpCode") != null
					&& session.getAttribute("otpCode").equals(otpCode)) {
				int accId1 = Integer.parseInt(session.getAttribute("accId1")
						.toString());
				transactionService.transaction(accId1, accId2, amount, 0);
				session.removeAttribute("accId1");
				session.removeAttribute("accId2");
				session.removeAttribute("amount");
				session.removeAttribute("countTran");
				session.removeAttribute("balance");
				modelAndView.addObject("transMess", "Transacsion is success!");
			} else {
				countTran++;
				session.setAttribute("countTran", countTran);
				if (countTran < 4) {
					modelAndView.setViewName("internaltransaction4.tile");
					modelAndView.addObject("errOTP", rb.getObject("errOTP"));
				} else {
					session.removeAttribute("accId1");
					session.removeAttribute("accId2");
					session.removeAttribute("amount");
					session.removeAttribute("countTran");
					session.removeAttribute("balance");
					modelAndView.addObject("transMess", "Transacsion failed!");
				}
			}

		}
		return modelAndView;
	}
}